package com.btkjgc.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lzh
 */
public class DateUtils {

	public static final String YYYY_MM_DD = "yyyy-MM-dd";

	public static final String YYYYMMDD = "yyyyMMdd";

	public static final String YYYY_MM_DD_SEC = "yyyy-MM-dd HH:mm:ss";

	public static java.util.Date getDateTimeFromString(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getOnlyStringDateWeekAgo() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date currentDate = new Date();
		long weekAgo = (currentDate.getTime() / 1000) - 60 * 60 * 24 * 7;
		currentDate.setTime(weekAgo * 1000);

		return sdf.format(currentDate);
	}

	public static String getDBFomatDate(String date) {
		String[] tempDate = date.split("/");
		date = tempDate[2] + "-" + tempDate[0] + "-" + tempDate[1];
		return date;
	}

	public static String getCSTtoNumberDate(String stringDate) {
		SimpleDateFormat sdf = new SimpleDateFormat(
				"EEE MMM ddHH:mm:ss 'CST' yyyy", Locale.US);
		Date date = null;
		try {
			date = sdf.parse(stringDate);
			sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sdf.format(date);

	}

	// 获取下一周的日期

	public Date nextWeek(Date currentDate) {

		GregorianCalendar cal = new GregorianCalendar();

		cal.setTime(currentDate);

		cal.add(GregorianCalendar.DATE, 7);// 在日期上加7天

		return cal.getTime();

	}

	// 获取本周日的日期

	public Date getSunday(Date monday) {

		GregorianCalendar cal = new GregorianCalendar();

		cal.setTime(monday);

		cal.add(GregorianCalendar.DATE, 6);// 在日期上加6天

		return cal.getTime();

	}

	// 获取下一月的日期

	public Date nextMonth(Date currentDate) {

		GregorianCalendar cal = new GregorianCalendar();

		cal.setTime(currentDate);

		cal.add(GregorianCalendar.MONTH, 1);// 在月份上加1

		return cal.getTime();

	}

	// 获取上一个月的日期
	public Date previousMonth(Date currentDate) {
		GregorianCalendar cal = new GregorianCalendar();

		cal.setTime(currentDate);

		cal.add(GregorianCalendar.MONTH, -1);// 在月份上加1

		return cal.getTime();
	}

	/**
	 * 得到某年某月的第一天
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public Date getFirstDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return cal.getTime();
	}

	/**
	 * 得到某年某月的最后一天
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public Date getLastDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, value);
		return cal.getTime();
	}

	/**
	 * 得到某年某月的某一周的第一天 author:wsr
	 */
	public Date getFirstDayOfWeek(int year, int month, int week) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		for (int i = 1; i < 8; i++) {
			cal.set(Calendar.DATE, i);
			if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 1) {// 判断当前天如果是周一
				break;
			}
		}
		cal.set(Calendar.DATE, ((week - 1) * 7) + cal.get(Calendar.DATE));
		return cal.getTime();
	}

	public Date getFirstDayOfWeek2(int year, int month, int week) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DATE, ((week - 1) * 7) + 1);
		return cal.getTime();
	}

	/*
	 * 得到某年某月的某一周的最后一天 author:wsr
	 */
	public Date getLastDayOfWeek(int year, int month, int week) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		for (int i = 1; i < 8; i++) {
			cal.set(Calendar.DATE, i);
			if (cal.get(Calendar.DAY_OF_WEEK) - 1 == 1) {// 判断当前天如果是周一
				break;
			}
		}
		cal.set(Calendar.DATE, ((week - 1) * 7) + cal.get(Calendar.DATE) + 6);
		return cal.getTime();
	}

	public Date getLastDayOfWeek2(int year, int month, int week) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		int day = cal.getActualMaximum(Calendar.DATE);
		if (week == 4) {
			cal.set(Calendar.DATE, day);
		} else {
			cal.set(Calendar.DATE, week * 7);
		}
		return cal.getTime();
	}

	// 获取下一年的日期

	public Date nextYear(Date currentDate) {

		GregorianCalendar cal = new GregorianCalendar();

		cal.setTime(currentDate);

		cal.add(GregorianCalendar.YEAR, 1);// 在年上加1

		return cal.getTime();

	}

	/**
	 * 时间。是否在此范围内 不在返回真 在。假
	 * 
	 * @param date
	 *            时间
	 * @param fromDate
	 *            开始时间
	 * @param toDate
	 *            结束时间
	 * @return
	 */
	public static Boolean compare(Date date, Date fromDate, Date toDate) {
		Calendar date1 = Calendar.getInstance();
		date1.setTime(date);
		Calendar from = Calendar.getInstance();
		from.setTime(fromDate);
		Calendar to = Calendar.getInstance();
		to.setTime(toDate);

		if (date1.after(from) && date1.before(to)) {
			return false;
		}
		return true;

	}

	/**
	 * 开始时间特殊处理一下
	 * 
	 * @param endTime
	 * @return
	 */
	public static Date getBeginTime(Date beginTime) {
		Calendar date1 = Calendar.getInstance();
		date1.setTime(beginTime);
		date1.set(Calendar.MINUTE, 00);
		date1.set(Calendar.HOUR_OF_DAY, 00);
		date1.set(Calendar.SECOND, 00);
		return date1.getTime();
	}

	/**
	 * 结束时间特殊处理一下
	 * 
	 * @param endTime
	 * @return
	 */
	public static Date getEndTime(Date endTime) {
		Calendar date1 = Calendar.getInstance();
		date1.setTime(endTime);
		date1.set(Calendar.MINUTE, 59);
		date1.set(Calendar.HOUR_OF_DAY, 23);
		date1.set(Calendar.SECOND, 59);
		return date1.getTime();
	}

	/**
	 * 返回当前日期
	 */
	public static String getCurrentDate() {
		Calendar date1 = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date1.getTime());
	}

	/**
	 * 返回当月第一天
	 */
	public static String getFirstDayOfMonth() {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar lastDate = Calendar.getInstance();
		lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
		str = sdf.format(lastDate.getTime());
		return str;
	}

	public static String getFirstDayOfYear() {
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar lastDate = Calendar.getInstance();
		lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
		lastDate.set(Calendar.MONTH, 0);// 设为1月
		str = sdf.format(lastDate.getTime());
		return str;
	}

	/**
	 * 为真前一天 为假后一天
	 */
	public static String getCurrentDate(boolean bool) {
		Calendar date1 = Calendar.getInstance();
		if (bool) {
			date1.add(Calendar.DATE, -1);
		} else {
			date1.add(Calendar.DATE, 1);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date1.getTime());
	}

	/**
	 * 为真前一天 为假后一天
	 * 
	 * @param bool
	 * @param currentDate
	 * @return
	 */
	public static String getCurrentDate(boolean bool, String currentDate) {
		Calendar date1 = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		date1.setTime(date);

		if (bool) {
			date1.add(Calendar.DATE, -1);
		} else {
			date1.add(Calendar.DATE, 1);
		}

		return sdf.format(date1.getTime());
	}

	/**
	 * 为真当月第一天 为假下个月第一天
	 * 
	 * @param bool
	 * @param currentDate
	 * @return
	 */
	public static String getCurrentMonth(boolean bool, String currentDate) {
		Calendar date1 = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		date1.setTime(date);
		date1.set(Calendar.DATE, 1);

		if (bool) {

		} else {
			date1.add(Calendar.MONTH, 1);

		}

		return sdf.format(date1.getTime());
	}

	/**
	 * 为真当年第一天 为假下年第一天
	 * 
	 * @param bool
	 * @param currentDate
	 * @return
	 */
	public static String getCurrentYear(boolean bool, String currentDate) {
		Calendar date1 = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(currentDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		date1.setTime(date);
		date1.set(Calendar.DATE, 1);
		date1.set(Calendar.MONTH, 1);
		if (bool) {

		} else {
			date1.add(Calendar.YEAR, 1);
		}

		return sdf.format(date1.getTime());
	}

	/**
	 * 用途：以指定的格式格式化日期字符串
	 * 
	 * @param pattern
	 *            字符串的格式
	 * @param currentDate
	 *            被格式化日期
	 * @return String 已格式化的日期字符串
	 * @throws NullPointerException
	 *             如果参数为空
	 */
	public static String formatDate(Object currentDate, String pattern) {
		if (currentDate == null || pattern == null) {
			throw new NullPointerException("The arguments are null !");
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(currentDate);
	}

	public static Date parseDate(String dateStr, String format) {
		Date date = null;
		try {
			date = new SimpleDateFormat(format).parse(dateStr);
		} catch (Exception e) {

			throw new IllegalArgumentException("日期转成时间报错");
		}
		return date;
	}

	/**
	 * 比较两个日期大小
	 * 
	 * @param date1
	 *            日期字符串
	 * @param pattern1
	 *            日期格式
	 * @param date2
	 *            日期字符串
	 * @param pattern2
	 *            日期格式
	 * @return boolean 若是date1比date2小则返回true
	 * @throws ParseException
	 */
	public static boolean compareMinDate(String date1, String pattern1,
			String date2, String pattern2) throws ParseException {
		try {
			Date d1 = parseDate(date1, pattern1);
			Date d2 = parseDate(date2, pattern2);
			return d1.before(d2);
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * 比较两个日期大小
	 * 
	 * @param date1
	 *            Date
	 * @param date2
	 *            Date
	 * @return boolean 若是date1比date2小则返回true
	 */
	public static boolean compareMinDate(Date date1, String pattern1,
			Date date2, String pattern2) {
		try {
			return compareMinDate(formatDate(date1, pattern1), pattern1,
					formatDate(date2, pattern2), pattern2);
		} catch (Exception ex) {
			return false;
		}
	}

	/**
	 * 获取当前日期(yyyy-MM-dd)
	 * 
	 * @return String型数据
	 */
	public static String getDay() {
		return getDay(YYYY_MM_DD);
	}

	/**
	 * 获取当前日期
	 * 
	 * @param dateFormat
	 * @return String型数据
	 */
	public static String getDay(String dateFormat) {
		Calendar cal = Calendar.getInstance();
		if (dateFormat == null || !"".equals(dateFormat)) {
			dateFormat = YYYY_MM_DD;
		}
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
		String mDateTime = formatter.format(cal.getTime());
		return mDateTime;
	}

	public static String getDateTime() {
		return getDateTime(YYYY_MM_DD_SEC);
	}

	public static String getDateTime(String dateFormat) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
		String mDateTime = formatter.format(cal.getTime());
		return (mDateTime);
	}

	public static String getDateTime(long milliseconds) {
		SimpleDateFormat formatter = new SimpleDateFormat(YYYY_MM_DD_SEC);
		return formatter.format(new Date(milliseconds));
	}

	/**
	 * 获取当前日期 （yyyy-MM-dd HH:mm:ss"）
	 * 
	 * @return
	 */
	public static Date getDate() {
		return getDate(YYYY_MM_DD_SEC);
	}

	/**
	 * 根据传入格式获取当前日期
	 * 
	 * @param dateFormat
	 * @return
	 */
	public static Date getDate(String dateFormat) {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
		String mDateTime = formatter.format(cal.getTime());
		return toDate(mDateTime, YYYY_MM_DD_SEC);
	}

	/**
	 * 两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 秒数
	 */
	public static Long getDateIntervalSecond(Date startDate, Date endDate) {
		Long sec = new Long("0");
		if (startDate != null) {
			if (endDate == null) {
				endDate = getDate();
			}
			sec = (Math.abs(startDate.getTime() - endDate.getTime())) / 1000;
		}
		return sec;
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 分钟数
	 */
	public static Long getDateIntervalMinute(Date startDate, Date endDate) {
		Long sec = getDateIntervalSecond(startDate, endDate);
		Long minute = sec / 60;
		return minute;
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 小时数
	 */
	public static Long getDateIntervalHour(Date startDate, Date endDate) {
		Long sec = getDateIntervalSecond(startDate, endDate);
		Long hour = sec / 3600;
		return hour;
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 天数
	 */
	public static Long getDateIntervalDay(Date startDate, Date endDate) {
		Long sec = getDateIntervalSecond(startDate, endDate);
		Long day = sec / (24 * 3600);
		return day;
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 月数
	 */
	@SuppressWarnings("deprecation")
	public static Long getDateIntervalMonth(Date startDate, Date endDate) {
		Long mon = new Long("0");
		if (startDate != null) {
			if (endDate == null) {
				endDate = getDate();
			}
			Date begin, end;
			if (startDate.getTime() > endDate.getTime()) {
				begin = endDate;
				end = startDate;
			} else {
				begin = startDate;
				end = endDate;
			}
			mon = new Long(
					((end.getYear() - begin.getYear()) * 12 + (end.getMonth() - begin
							.getMonth())));
		}
		return mon;
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 毫秒数
	 */
	public static long getDateInterval(String startDate, String endDate) {
		Date d1 = null;
		Date d2 = null;
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d1 = dateFormatter.parse(startDate);
			d2 = dateFormatter.parse(endDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return getDateInterval(d1, d2);
	}

	/**
	 * 获取两个时间段的间隔
	 * 
	 * @param startDate
	 * @param endDate
	 * @return 毫秒数
	 */
	public static long getDateInterval(Date startDate, Date endDate) {
		long day = (startDate.getTime() - endDate.getTime())
				/ (1000 * 60 * 60 * 24);
		return day;
	}

	/**
	 * 获取第N个星期
	 * 
	 * @param date
	 * @return
	 */
	public static int getWeek(Date date) {
		SimpleDateFormat weekFormat = new SimpleDateFormat("E");
		String returnValue = weekFormat.format(date);
		return Integer.parseInt(returnValue);
	}

	/**
	 * String日期转换成Date型日期(严格格式)
	 * 
	 * @param string
	 * @param pattern
	 * @return
	 */
	public static Date formatStringToDateStrict(String string, String pattern) {
		return formatStrToDate(string, pattern, false);
	}

	/**
	 * String日期转换成Date型日期(非严格格式)
	 * 
	 * @param string
	 * @param pattern
	 * @return
	 */
	public static Date formatStringToDateNoStrict(String string, String pattern) {
		return formatStrToDate(string, pattern, true);
	}

	public static boolean isValidateDate(String sDate) {
		if (null == sDate || "".equals(sDate)) {
			return false;
		}
		boolean flag = false;
		Pattern pattern0 = null;
		Matcher match0 = null;

		String datePattern = "("
				+
				// 第一种情况为月份是大月的有31天。
				"(^\\d{3}[1-9]|\\d{2}[1-9]\\d{1}|\\d{1}[1-9]\\d{2}|[1-9]\\d{3}"
				+ // 年
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"(10|12|0?[13578])"
				+ // 大月
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"((3[01]|[12][0-9]|0?[1-9])?)"
				+ // 日(31)要验证年月因此出现0/1次
				"([\\s]?)"
				+ // 空格
				"((([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9]))?))$"
				+ // 时分秒
				"|"
				+ // 或
					// 第二种情况为月份是小月的有30天，不包含2月。
				"(^\\d{3}[1-9]|\\d{2}[1-9]\\d{1}|\\d{1}[1-9]\\d{2}|[1-9]\\d{3}"
				+ // 年
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"(11|0?[469])"
				+ // 小月不含2月
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"(30|[12][0-9]|0?[1-9])"
				+ // 日(30)
				"([\\s]?)"
				+ // 空格
				"((([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9]))?))$"
				+ // 时分秒
				"|"
				+ // 或
					// 第三种情况为平年月份是2月28天的。
				"(^\\d{3}[1-9]|\\d{2}[1-9]\\d{1}|\\d{1}[1-9]\\d{2}|[1-9]\\d{3}"
				+ // 年
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"(0?2)"
				+ // 平年2月
				"([-]?)"
				+ // 时间间隔符(-,/,.,_)
				"(2[0-8]|1[0-9]|0?[1-9])"
				+ // 日(28)
				"([\\s]?)"
				+ // 空格
				"((([0-1]?[0-9]|2[0-3]):([0-5]?[0-9]):([0-5]?[0-9]))?))$"
				+ // 时分秒
				"|"
				+ // 或
					// 第四种情况为闰年月份是2月29天的。
					// 可以被4整除但不能被100整除的年份。
					// 可以被400整除的数亦是能被100整除，因此后两位是00，所以只要保证前两位能被4整除即可。
				"(^((\\d{2})(0[48]|[2468][048]|[13579][26]))|((0[48]|[2468][048]|[13579][26])00)"
				+ "([-]?)" + "(0?2)" + "([-]?)" + "(29)" + "([\\s]?)"
				+ "((([0-1]?\\d|2[0-3]):([0-5]?\\d):([0-5]?\\d))?))$" + // 时分秒
				")";
		;

		pattern0 = Pattern.compile(datePattern);
		match0 = pattern0.matcher(sDate);
		flag = match0.matches();
		return flag;
	}

	private static Date formatStrToDate(String string, String pattern,
			boolean isLenient) {
		SimpleDateFormat dateFormat = new SimpleDateFormat();
		if (pattern != null) {
			dateFormat.applyPattern(pattern);
		} else {
			dateFormat.applyPattern(YYYY_MM_DD);
		}
		if ((string == null) || (string.equals(""))) {
			return null;
		} else {
			try {
				dateFormat.setLenient(isLenient);
				return dateFormat.parse(string);
			} catch (ParseException e) {
				return null;
			}
		}
	}

	/**
	 * Date型日期转换成String日期
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDateToStringWithNull(Date date, String pattern) {
		SimpleDateFormat dateFormat = new SimpleDateFormat();
		if (pattern != null) {
			dateFormat.applyPattern(pattern);
		} else {
			dateFormat.applyPattern(YYYY_MM_DD);
		}
		if (date == null) {
			return null;
		} else {
			return dateFormat.format(date);
		}

	}

	/*
	 * public static String formatDateStr( String dateStr ) { String tmp1 =
	 * dateStr.substring( 0, 4 ); String tmp2 = dateStr.substring( 5, 7 );
	 * String tmp3 = dateStr.substring( 8, 10 ); String tmp = tmp1 + tmp2 +
	 * tmp3; return tmp; }
	 */
	/**
	 * 转换成日期型数据
	 * 
	 * @param value
	 * @param dateFormat
	 * @return
	 */
	public static Date toDate(String value, String dateFormat) {

		Date d = null;
		SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
		try {
			d = dateFormatter.parse(value);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}

	/**
	 * 转换成秒
	 * 
	 * @param day
	 * @param hour
	 * @param minutes
	 * @return
	 */
	public static int convert2Second(int day, int hour, int minutes) {
		int seconds = 0;
		if (day > 0) {
			seconds += 24 * 60 * 60 * day;
		}
		if (hour > 0) {
			seconds += 60 * 60 * hour;
		}
		if (minutes > 0) {
			seconds += 60 * minutes;
		}
		return seconds;
	}

}
